﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Directory.Web
{
	public partial class AddItem : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				ccCategories.DataSource = CategoryDataProxy.GetChildsOfCategory(WebSettings.GetInstance().RootCategoryId);
				ccCategories.DataBind();
				int categoryId;
				if (int.TryParse(Request.QueryString["categoryId"], out categoryId))
				{
					IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(categoryId);
					string path = null;
					foreach (Directory.Model.CategoryInfo cat in parentPath)
					{
						path += cat.CategoryId.ToString() + ",";
					}
					if (path != null)
					{
						ccCategories.AutoLoad = true;
						ccCategories.SelectedIndexStr = path.Remove(path.Length - 1);
					}
				}
				else
				{
					ccCategories.SelectedIndex = 0;
				}
			}
		}

		// 推荐
		protected void btnRecommend_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(tbTitle.Text))
			{
				ltMsg.Text = "标题不能为空。";
				return;
			}
			if (string.IsNullOrEmpty(tbLinkUrl.Text))
			{
				ltMsg.Text = "链接地址不能为空。";
				return;
			}
			Directory.Model.ItemInfo.ErrorCode errorCode;
			try
			{
				string username = Page.User.Identity.IsAuthenticated ? Page.User.Identity.Name : WebSettings.GetInstance().AnonymousUserName;
				ItemDataProxy.CreateItem(ccCategories.SelectedId, tbTitle.Text, string.Empty, tbDescription.Text, tbLinkUrl.Text, "/default.gif", username, username, 0, false, false, out errorCode);
			}
			catch
			{
				ltMsg.Text = "添加失败：服务器错误。";
				return;
			}
			switch (errorCode)
			{
				case Directory.Model.ItemInfo.ErrorCode.Success:
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('添加成功！');window.location.href='additem.aspx?categoryId="+ccCategories.SelectedId+"'</script>");
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidTitle:
					ltMsg.Text = "添加失败：标题不正确。";
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidCategory:
					ltMsg.Text = "添加失败：目录不可用。";
					break;
				default:
					ltMsg.Text = "添加失败：未知错误。";
					break;
			}
		}
	}
}